package icu.lookyousmileface.netty.simple

import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelOption
import io.netty.channel.EventLoopGroup
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioServerSocketChannel


/**
 * @title: NettyServer
 * @projectName NettyPro
 * @author shenj
 * @date 2020/12/3 16:15
 */
fun main() {

    //获得MainReactor和WorkerReactor的无限轮询
    val mainEventGroup: EventLoopGroup = NioEventLoopGroup()
    val workerEventGroup: EventLoopGroup = NioEventLoopGroup()
    try {

        //创建Server StartApplication 对象
        val startApplicationConfiguration = ServerBootstrap()

        //设置startApplication对象的参数
        startApplicationConfiguration.group(mainEventGroup, workerEventGroup)
                .channel(NioServerSocketChannel::class.java)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(object : ChannelInitializer<io.netty.channel.socket.SocketChannel>() {
                    override fun initChannel(ch: io.netty.channel.socket.SocketChannel) {
                        ch.pipeline().addLast(NettyHandler())
                    }
                })
        println("Server is ready....")

        val channelFuture: ChannelFuture = startApplicationConfiguration.bind(7788).sync()

//    监听通道关闭事件，同步
        channelFuture.channel().closeFuture().sync()

    } finally {
        mainEventGroup.shutdownGracefully()
        workerEventGroup.shutdownGracefully()
    }

}